/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.booting.balancer4j;

import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/**
 * A default base class for a {@link LoadBalancer} implementation.
 */
public abstract class LoadBalancerSupport<T, R> implements LoadBalancer<T, R> {

    private final AtomicReference<Candidate<T, R>[]> candidates = new AtomicReference<Candidate<T, R>[]>(new Candidate[0]);
    @Getter
    @Setter
    private String id;

    public void add(final Candidate<T, R> candidate) {
        candidates.updateAndGet(op -> doAdd(candidate, op));
    }

    public void remove(Candidate<T, R> Candidate) {
        candidates.updateAndGet(op -> doRemove(Candidate, op));
    }

    @Override
    public void build(Supplier<List<Candidate<T, R>>> supplier) {
        candidates.set(supplier.get().toArray(new Candidate[0]));
    }

    private Candidate<T, R>[] doAdd(Candidate<T, R> Candidate, Candidate<T, R>[] op) {
        int len = op.length;
        Candidate<T, R>[] np = Arrays.copyOf(op, len + 1, op.getClass());
        np[len] = Candidate;
        return np;
    }

    private Candidate<T, R>[] doRemove(Candidate<T, R> Candidate, Candidate<T, R>[] op) {
        int len = op.length;
        for (int index = 0; index < len; index++) {
            if (op[index].equals(Candidate)) {
                Candidate<T, R>[] np = (Candidate[]) Array.newInstance(Candidate.class, len - 1);
                System.arraycopy(op, 0, np, 0, index);
                System.arraycopy(op, index + 1, np, index, len - index - 1);
                return np;
            }
        }
        return op;
    }

    public List<Candidate<T, R>> candidates() {
        return Arrays.<Candidate<T, R>>asList(candidates.get());
    }

    protected Candidate<T, R>[] doGetCandidates() {
        return candidates.get();
    }

    public List<Candidate<T, R>> next() {
        if (!hasNext()) {
            return null;
        }
        return candidates();
    }

    public boolean hasNext() {
        return doGetCandidates().length > 0;
    }

    public boolean isRunAllowed() {
        return true;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + Arrays.toString(doGetCandidates());
    }

}
